import { TodosContext } from '../contexts/todo';
import cn from 'classnames';
import { useTodoActions } from '../hooks/useTodoActions';
import type { TodoItem } from '../machines/todosMachine';

export function Todo({ todo }: { todo: TodoItem }) {
  const { id, completed } = todo;
  const { send, title, isEditing, inputRef } = useTodoActions(todo);
  const todosActorRef = TodosContext.useActorRef();

  return (
    <li
      className={cn({
        editing: isEditing,
        completed
      })}
      data-todo-state={completed ? 'completed' : 'active'}
      key={id}
    >
      <div className="view">
        <input
          className="toggle"
          type="checkbox"
          onChange={(ev) => {
            todosActorRef.send({
              type: 'todo.mark',
              id: todo.id,
              mark: ev.target.checked ? 'completed' : 'active'
            });
          }}
          checked={completed}
        />
        <label
          onDoubleClick={() => {
            send({ type: 'edit' });
          }}
        >
          {title}
        </label>{' '}
        <button
          className="destroy"
          onClick={() =>
            todosActorRef.send({
              type: 'todo.delete',
              id: todo.id
            })
          }
        />
      </div>
      <input
        className="edit"
        value={title}
        onBlur={() => send({ type: 'blur' })}
        onChange={(ev) => {
          send({
            type: 'change',
            value: ev.target.value
          });
        }}
        onKeyDown={(ev) => {
          if (ev.key === 'Enter') {
            send({ type: 'blur' });
          } else if (ev.key === 'Escape') {
            send({ type: 'cancel' });
          }
        }}
        ref={inputRef}
      />
    </li>
  );
}
